package org.ccf.certified.controller.base;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.ccf.certified.bean.ResponseBean;
import org.ccf.certified.business.shiro.manager.TokenVerifyManager;
import org.ccf.certified.business.shiro.manager.UserManager;
import org.ccf.certified.business.shiro.model.TokenVerify;
import org.ccf.certified.business.shiro.model.User;
import org.ccf.certified.util.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author LiuFang
 * @date 2022/1/12
 */
@RestController
public class WebController {

    private static final Logger log = LoggerFactory.getLogger(WebController.class);

    @Value("${token.timeout}")
    private Integer TOKEN_TIMEOUT;

    @Autowired
    private UserManager userService;

    @Autowired
    private TokenVerifyManager tokenVerifyManager;

    @PostMapping("/login")
    public ResponseBean login(@RequestParam("username") String username,
                              @RequestParam("password") String password) {
        User userBean = userService.getUser(username);
        if (userBean.getPassword().equals(password)) {
            String token = JWTUtil.sign(username, password);
            /** 将Token存储到数据库*/
            Date date = new Date();
            date.setTime(date.getTime() + TOKEN_TIMEOUT);
            boolean save = tokenVerifyManager.save(new TokenVerify(token, date, 1, userBean.getId()));
            if(save){
                return ResponseBean.getResultsSuccess(token);
            }else {
                return ResponseBean.getResultsFail();
            }
        } else {
            throw new UnauthorizedException();
        }
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseBean unauthorized() {
        return new ResponseBean(401, "Unauthorized", "请重新登录,无效访问...");
    }


    /** 以下为测试接口,可以进行删除 */

    @GetMapping("/article")
    public ResponseBean article() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return new ResponseBean(200, "You are already logged in", null);
        } else {
            return new ResponseBean(200, "You are guest", null);
        }
    }

    @GetMapping("/require_auth")
    @RequiresAuthentication
    public ResponseBean requireAuth() {
        return new ResponseBean(200, "You are authenticated", null);
    }

    @GetMapping("/require_role")
    @RequiresRoles("admin")
    public ResponseBean requireRole() {
        return new ResponseBean(200, "You are visiting require_role", null);
    }

    @GetMapping("/require_permission")
    @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})
    public ResponseBean requirePermission() {
        return new ResponseBean(200, "You are visiting permission require edit,view", null);
    }
}
